import { createRouter, createWebHashHistory } from 'vue-router'
import ai1 from '../views/Qianfan.vue'
import ai2 from '../views/Qianwen.vue'
import aiimg from '../views/Txt2Img.vue'
import reg from '../views/Reg2.vue'
import login from '../views/Login2.vue'
import reclist from '../views/AIRecordList2.vue'
import history from '../views/history.vue'
const routes = [
  {
    path: '/ai/qianfan',
    name: 'ai1',
    component: ai1,
    meta: {
      title: '千帆',
      needLogin: true,
    }
  },
  {
    path: '/ai/qianwen',
    name: 'ai2',
    component: ai2,
    meta: {
      title: '千问',
      needLogin: true,
    }
  },
  {
    path: '/ai/image',
    name: 'aiimg',
    component: aiimg,
    meta: {
      title: '图片生成',
      needLogin: true,
    }
  },
  {
    path: '/ai/record',
    name: 'record',
    component: reclist,
    meta: {
      title: '记录',
      needLogin: true,
    }
  },
  {
    path: '/ai/history',
    name: 'history',
    component: history,
    meta: {
      title: '历史',
      needLogin: true,
    }
  },
  {
    path: '/reg',
    name: 'reg',
    component: reg,
  },
  {
    path: '/login',
    name: 'login',
    component: login,
  },

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
//在跳转之前：to是当前页面，from是想跳转到的页面，next是实际上到达的页面，若未指定则就会跳转from
router.beforeEach((to, from, next) => {
  if (!to.meta.needLogin)
    // 判断该路由是否需要登录权限
    next();
  else if (to.meta.needLogin == true) {
    // 若当前页面需要登录
    if (sessionStorage.getItem('user') == null) {
      // 用户未登录，重定向到登录页
      alert('请先登录！');
      next('/login');
    } else {
      // 用户已登录，直接访问
      next();
    }
  }
});

export default router
